<template>
  <el-drawer
    v-model="renderVisible"
    :title="props.title"
    destroy-on-close
    :size="props.size"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :label-position="'top'"
      label-width="160px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="规格标题" prop="title">
        <el-input
          v-model="formData.title"
          :maxlength="32"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="规格内容" prop="content">
        <div class="tag-box">
          <el-tag
            v-for="(item, index) in tagOpts.list"
            :key="item"
            closable
            size="default"
            type="info"
            effect="plain"
            :disable-transitions="false"
            @close="handleRemoveTag(index)"
            >{{ item }}</el-tag
          >
          <el-input
            v-if="tagOpts.visible"
            class="tag-ipt"
            v-model="tagOpts.value"
            :maxlength="16"
            @keyup.enter="handleAddTag"
            @blur="handleAddTag"
          />
          <el-button v-else class="tag-btn" @click="tagOpts.visible = true"
            >+ 添加规格</el-button
          >
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <PipeResetBtn :formEl="formRef">重置</PipeResetBtn>
      <el-button
        type="primary"
        @click="handleClickSubmit(formRef)"
        :loading="isLoading"
        >提交</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref, watch, computed, PropType } from 'vue';
import type { ElForm } from 'element-plus';
import { ElMessage } from 'element-plus';

import { createGoodsSpecs, updateGoodsSpecs } from '@/apis/goods-specs';
import { loopPropAssignment } from '@/utils/util';

// 加载状态
const isLoading = ref(false);

// 表单ref
const formRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const GetFormData = (): API.goodsSpecs.EntityDto => ({
  title: '',
  content: ''
});
const formData = reactive(GetFormData());

const formRules = reactive({
  title: [
    {
      type: 'string',
      required: true,
      trigger: 'blur',
      message: '请输入规格标题'
    }
  ],
  content: [
    {
      type: 'string',
      required: true,
      trigger: 'blur',
      message: '请输入规格内容'
    }
  ]
});

// 标签
const tagOpts = reactive<{
  visible: boolean;
  value: string;
  list: string[];
}>({
  // 是否显示添加规格input
  visible: false,
  // 规格input绑定的值
  value: '',
  // 规格内容 - 标签样式
  list: []
});

// 添加标签
const handleAddTag = () => {
  if (tagOpts.value) {
    tagOpts.list.push(tagOpts.value);
  }
  tagOpts.visible = false;
  tagOpts.value = '';

  // 更新值
  formData.content = tagOpts.list.join(',');
};

// 移除标签
const handleRemoveTag = (index: number) => {
  // 根据index移除项
  tagOpts.list.splice(index, 1);

  // 更新值
  formData.content = tagOpts.list.join(',');
};

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },

  title: String,

  size: {
    type: [String, Number],
    default: '30%'
  },

  isEdit: {
    type: Boolean,
    default: false
  },

  rowData: {
    type: Object as PropType<API.goodsSpecs.TableData>,
    default: () => ({})
  }
});

// emits
const emits = defineEmits(['update:modelValue', 'onRefresh']);

// computed - 抽屉[显示|隐藏]
const renderVisible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// watch
watch(
  () => props.modelValue,
  (val) => {
    if (!val) return;

    // 当rowData发生变化，初始化数据
    loopPropAssignment(formData, props.isEdit ? props.rowData : GetFormData());
    // 切割规格
    tagOpts.list = formData.content ? formData.content.split(',') : [];
  },
  {
    immediate: true
  }
);

// btn - submit
const handleClickSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
  if (!formEl) return;

  formEl.validate(async (valid) => {
    if (!valid) return;
    if (props.isEdit) {
      submitDataUpdate();
    } else {
      submitDataAdd();
    }
  });
};

// submit - add
const submitDataAdd = () => {
  isLoading.value = true;
  createGoodsSpecs(formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// submit - update
const submitDataUpdate = () => {
  isLoading.value = true;
  updateGoodsSpecs(props.rowData.id!, formData)
    .then((res) => {
      isLoading.value = false;
      ElMessage.success(res.message);
      // 关闭弹窗
      emits('onRefresh');
      renderVisible.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
</script>

<style lang="scss" scoped>
.tag-box {
  .el-tag {
    margin: 0 8px 8px 0;
  }
  .tag-ipt {
    width: 90px;
    margin: 0 8px 8px 0;
  }
  .tag-btn {
    margin: 0 8px 8px 0;
  }
}
</style>
